package com.ck.mybatis.plus.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ck.mybatis.plus.model.CkPageInfo;
//import com.github.pagehelper.Page;
import com.github.pagehelper.Page;
import org.dozer.DozerBeanMapper;
import org.dozer.loader.api.BeanMappingBuilder;
import org.dozer.loader.api.TypeMappingOption;
import org.dozer.loader.api.TypeMappingOptions;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Classname MapperUtils
 * @Description TODO
 * @Date 2020/7/13 0:54
 * @Created by lpc
 */
public class MapperUtils {

    public MapperUtils() {
    }

    public static <T, U> List<U> mappingList(final List<T> source, final Class<U> destType) {
        if (source == null) {
            return null;
        } else {
            List<U> dest = (List)source.stream().filter((v1) -> {
                return v1 != null;
            }).map((v2) -> {
                U v3 = mapping(v2, destType);
                return v3;
            }).collect(Collectors.toList());
            return dest;
        }
    }

    public static <T, U> U mapping(T source, final Class<U> destType) {
        if (source == null) {
            return null;
        } else {
            WeakReference weakReference = new WeakReference(new DozerBeanMapper());
            DozerBeanMapper mapper = (DozerBeanMapper)weakReference.get();
            mapper.addMapping(new BeanMappingBuilder() {
                protected void configure() {
                    this.mapping(source.getClass(), destType, new TypeMappingOption[]{TypeMappingOptions.mapNull(false), TypeMappingOptions.mapEmptyString(true)});
                }
            });
            U result = mapper.map(source, destType);
            mapper.destroy();
            return result;
        }
    }

    public static <T, U> CkPageInfo<T> mappingNcPage(IPage<U> page, Class T) {
        CkPageInfo<T> ncPageInfo = new CkPageInfo();
        ncPageInfo.setTotal((int)page.getTotal());
        ncPageInfo.setPageNum((int)page.getCurrent());
        ncPageInfo.setPageSize((int)page.getSize());
        List<U> records = page.getRecords();
        List<T> msgCenterVOS = mappingList(records, T);
        ncPageInfo.setData(msgCenterVOS);
        return ncPageInfo;
    }

    public static <T, U> CkPageInfo<T> mappingNcPage(Page<U> page, Class T) {
        CkPageInfo<T> ncPageInfo = new CkPageInfo();
        ncPageInfo.setTotal((int)page.getTotal());
        ncPageInfo.setPageNum(page.getPageNum());
        ncPageInfo.setPageSize(page.getPageSize());
        List<U> records = page.getResult();
        List<T> msgCenterVOS = mappingList(records, T);
        ncPageInfo.setData(msgCenterVOS);
        return ncPageInfo;
    }
}
